<template>
  <nut-uploader :auto-upload="true" :maximum="maximum" :url="uploadUrl" v-model:file-list="defaultFileList" method="post" :before-xhr-upload="beforeXhrUpload"></nut-uploader>
</template>
<script setup>
import axios from "axios";
import { ref, defineProps, computed, defineEmits, watch } from 'vue';
import { useUserStore } from '@/store/modules/user/index.js'
import { useVisaStore } from '@/store/modules/visa/index.js'
import { getToken } from '@/utils'
import { showToast } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/toast/style';
const emit = defineEmits(['changeFile', 'update:fileList'])
const props = defineProps({
  material: {
    type: Object,
    defalut () {
      return {}
    }
  },
  fileList: {
    type: Array,
  },
  defaultFileList: {
    type: Array,
  }
})
const maximum = ref(2)
let _fileList_ = props.fileList
let _fileList = ref([])
let defaultFileList = computed(() => {
  return props.defaultFileList.map((value, index, array) => {
    return { name: value.fileName || value.file_name, url: value.file_url, type: 'image', status: 'success' }
  })
})

watch(() => props.fileList.length, (newL) => {
  _fileList.value = props.fileList
}, { immediate: true })
const beforeXhrUpload = (xhr, options) => {
  if (options.method.toLowerCase() == 'post') {
    postFile(options.sourceFile)
  }
};
const uploadUrl = import.meta.env.VITE_BASE_URL + '/third/visa/upload/file';
const sign = useVisaStore().sign || window.sessionStorage.get('sign')
const postFile = (sourceFile) => {
  showToast.loading('图片上传中', { cover: true, duration: 0 });
  const form = new FormData();
  form.append("uid", useVisaStore().uId);
  form.append("sign", sign);
  form.append("file", sourceFile);
  const options = {
    method: 'POST',
    url: uploadUrl,
    headers: {
      Authorization: getToken(),
      'content-type': 'multipart/form-data; boundary=---011000010111000001101001'
    },
    data: form
  };
  axios.request(options).then(function (response) {
    const { code, data, success } = response.data
    if (+code === 200 && success) {
      // emit('changeFile', data)
      // const fileList = _fileList.push(data)
      // emit('update:fileList', fileList)
      emit('changeFile', data)
      showToast.hide()
      showToast.loading('图片上传成功', { cover: true, duration: 2000 });
    } else {
      showToast.hide()
      showToast.loading('图片上传失败', { cover: true, duration: 2000 });
    }
  }).catch(function (error) {
    showToast.hide()
    showToast.loading('图片上传失败', { cover: true, duration: 2000 });
  });
}
function deWeightTwo (arr2) {
  let temp = [];

  arr2.forEach(function (a) {
    var check = temp.every(function (b) {
      return a.name !== b.name;
    })
    check ? temp.push(a) : ''
  })
  return temp;
}

</script>